/*
 * @lc app=leetcode.cn id=904 lang=swift
 *
 * [904] 水果成篮
 */

// @lc code=start
class Solution {
    func totalFruit(_ tree: [Int]) -> Int {
        var window: [Int: Int] = [:]
        let k = 2
        var res = 0
        var left = 0
        for right in 0..<tree.count {
            let treeR = window[tree[right]] ?? 0
            window[tree[right]] = treeR + 1
            while window.count > k {
                window[tree[left]]! -= 1
                if window[tree[left]]! == 0 {
                    window.removeValue(forKey: tree[left])
                }
                left += 1
            }
            res = max(res, right - left + 1);
        }
        return res
    }
}
// @lc code=end

